import store from '@/store'
import { setToken } from '@/utils/auth'
import settings from '@/config/settings'

const tokenKey = '_t'
const systemTag = settings.appId

// 判断是否是登录中心跳转到子系统中
export const isRedirect = () => {
    return window.location.search.includes(tokenKey)
}

export const handleRedirect = () => {
    const location = window.location
    let query = location.search
    const tail = query.split('?')[1]
    const tokenKey = '_t'
    if (tail && tail.includes(tokenKey)) {
        const items = tail.split('&')
        const kvs = items.reduce((acc, item) => {
            const [key, value] = item.split('=')
            acc[key] = value
            return acc
        }, {})
        const token = kvs[tokenKey]

        // 登录中心跳转
        if (token) {
            let t = decrypt(token)
            t = decodeURI(t)
            store.commit('user/setToken', t)
            setToken(t)

            // 用 next 或 $router.push, query 参数去不掉
            const host = location.origin
            const path = location.pathname
            //
            delete kvs[tokenKey]

            query = Object.entries(kvs)
                .map(([k, v]) => {
                    return `${k}=${v}`
                })
                .join('&')
            const split = query ? '?' : ''
            const url = `${host}${path}${split}${query}`
            window.location.href = url
        }
    }
}

export const loginUrl = () => {
    // eslint-disable-next-line no-undef
    return api_source.loginUrl
}

export function toLoginCenter(redirect = true, logout = false, userCenter = false) {
    const url = loginUrl()
    if (url) {
        let path = url
        if (redirect) {
            const href = window.location.href
            path = `${url}?redirect=${href}&tag=${systemTag}`
        }

        if (logout) {
            path = `${url}/login?logout=1`
        }

        if (userCenter) {
            path = `${url}/user`
        }

        window.location.href = path
    }
}

// 对 url 中的 token 简单加密
const xorKey = '5432167890'
export function encrypt(data, key = xorKey) {
    const r = []
    for (let i = 0; i < data.length; i++) {
        const code = data.charCodeAt(i) ^ key.charCodeAt(i % key.length)
        r.push(code)
    }
    return r.join('-')
}

export function decrypt(data, key = xorKey) {
    const r = data.split('-').map((d, i) => {
        const m = Number(d)
        const code = m ^ key.charCodeAt(i % key.length)
        const s = String.fromCharCode(code)
        return s
    })
    return r.join('')
}
